# -*- coding: utf-8 -*-

import time
import hashlib
import requests
import urllib
import copy
import operator
import json
import hmac

class ubix():
    
    _headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
	'Accept': 'application/json'
    }

    def __init__(self, api_Key, secret_key):
        self.url = 'https://api.ubiex.co'
        self.api_Key = api_Key
        self.secret_key = secret_key
    def sign(self,kwargs: dict, secretKey: str):
        out = []
        for k, v in kwargs.items():
            out.append("{}={}".format(str(k).strip(), str(v).strip()))
        out.sort()
        s = "&".join(out)
        return hmac.new(secretKey.encode(), s.encode(), digestmod=hashlib.sha256).hexdigest().upper()
    
    def get(self,url,params):
        headers = dict(self._headers)
        postdata = urllib.parse.urlencode(params)
        try:
            response = requests.get(url, postdata, headers=headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                return data
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
    
    def get_sign(self,url,params):
        headers = dict(self._headers)
        postdata = urllib.parse.urlencode(params)
        try:
            response = requests.get(url, postdata, headers=headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') !=  200 :
                    print(data.get('info'),data.get('code'))
                return data.get('data')

            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
        
    def postt(self,url,params):
        headers = dict(self._headers)
        postdata =urllib.parse.urlencode(params)
        try:
            response = requests.post(url,postdata, headers=headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') !=  200 :
                    print(data.get('info'),data.get('code'))
                return data.get('data')
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
    
    def get_balance(self):
        dit = {
            "accesskey": self.api_Key,
            "nonce": int(time.time()*1000)
        }
        dit["signature"] = self.sign(dit,self.secret_key)
        url =self.url + '/trade/api/v1/getBalance'
        return self.get_sign(url,dit) 
    
    def take_order(self,market,price,number,otype,entrustType):
        dit = {
            "accesskey": self.api_Key,
            "nonce": int(time.time()*1000),
            "market": market,
            "price": price,
            "number": number,
            "type": otype,
            "entrustType": entrustType,
        }
        dit["signature"] = self.sign(dit,self.secret_key)
        url =self.url + '/trade/api/v1/order'
        return self.postt(url,dit)
    
    def get_ticker(self,market):
        params={}
        params['market']=market
        url =self.url + '/data/api/v1/getTicker'
        return self.get(url,params)
    
    def cancel_order(self,market,idd):
        dit = {
            "accesskey": self.api_Key,
            "nonce": int(time.time()*1000),
            "market": market,
            "id": idd
        }
        dit["signature"] = self.sign(dit,self.secret_key)
        url =self.url + '/trade/api/v1/cancel'
        return self.postt(url,dit)
    
    def get_orders(self,market):
        dit = {
            "accesskey": self.api_Key,
            "nonce": int(time.time()*1000),
            "market": market
        }
        dit["signature"] = self.sign(dit,self.secret_key)
        url =self.url + '/trade/api/v1/getOpenOrders'
        return self.get_sign(url,dit)
        
        